package m.base.service;

import m.appserver.AuthInfoUtil;
import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.RepositoryInfo;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.model.*;
import manage.service.AdminLoginService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserInfoService extends Service {
    /**
     * 添加用户
     */
    public UserInfo addUser(UserInfo model, StoreInfo store,String password) throws Exception {
        String oid=GenerateID.generatePrimaryKey();
        AdminLogin admin=new AdminLogin();
        admin.setUserNo(oid);
        admin.setUsername(model.getUsername());
        admin.setPassword(model.getPassword());
        admin.setRealname(model.getRealname());
        admin.setAdminGroup(new AdminGroup());
        admin.getAdminGroup().setOid("2");//用户组
        admin.setOrgGroup(new OrgGroupView());
        admin.getOrgGroup().setOid(store.getOid());
        AdminGroupLink link=new AdminGroupLink();
        link.setAdminGroup(new AdminGroup());
        link.getAdminGroup().setOid(store.getOid());
        link.setType(AdminGroup.Type_Org);
        ModelCheckUtil.checkUniqueCombine(model, new String[]{"username"},"员工号已存在");
        getService(AdminLoginService.class).save(admin,link,password,true);
        model.setOid(oid);
        model.setStore(store);
        ModelUpdateUtil.updateModel(model,"operType","phone","store.oid");
        return model;
    }
    public void save(UserInfo model) throws Exception {
        if("1".equals(model.getOid())) throw AuthInfoUtil.noPowerException;
        ModelQueryCheck.init(model)
            .checkNotNull("username","请输入员工号")
            .checkNotNull("realname","请输入员工名称")
            .checkNotNull("phone","请输入联系信息")
            //.checkNotNull("operType","请选择用户类型")
            .doCheck(false,true);
        ModelCheckUtil.checkUniqueCombine(model, new String[]{"username"},"员工号已存在");
        if(ObjectUtil.isEmptyOid(model)){
            if(StringUtil.isSpace(model.getPassword())) throw new MException(this.getClass(),"请输入员工码");
            model=addUser(model, PowerUtil.getSessionStore(true),model.getPassword());
        }
        if(StringUtil.isSpace(model.getPassword())){
            ModelUpdateUtil.updateModel(model,"username","realname","operType","phone");
        }else{
            model.setPassword(StringUtil.toMD5(model.getPassword()));
            ModelUpdateUtil.updateModel(model,"username","password","realname","operType","phone");
        }
        CacheUtil.clear(UserInfo.class,model.getOid());
        CacheUtil.clear(AdminLogin.class,model.getOid());
    }

    /**
     * 将用户数禁用剩num个
     */
    public void limitUserNum(String storeOid,int num) throws SQLException, MException {
        StoreInfo store=CacheUtil.get(StoreInfo.class,storeOid);
        List<UserInfo> us= ModelQueryList.getModelList(UserInfo.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("store.oid",storeOid),
                QueryCondition.eq("status",StatusModel.Status_Enable),
                QueryCondition.not(QueryCondition.eq("oid",store.getCreateUserOid()))
            ),QueryOrder.desc("oid")
        );
        if(us.size()<=num-1) return;
        List<UserInfo> nl=new ArrayList<>();
        for(int i=0;i<us.size()-(num-1);i++) nl.add(us.get(i));
        nl.forEach((item)->item.setStatus(StatusModel.Status_Disabled));
        ModelUpdateUtil.updateModels(nl.toArray(new UserInfo[]{}),"status");
        nl.forEach((model)->{
            CacheUtil.clear(UserInfo.class,model.getOid());
            CacheUtil.clear(AdminLogin.class,model.getOid());
        });
    }

    /**
     * 设置用户角色
     */
    public void setOperType(String userOid,String storeOid,String[] operType) throws MException, SQLException {
        UserInfo model=new UserInfo();
        model.setOid(userOid);
        model.setOperType(operType);
        model.setCreateStoreOid(storeOid);
        ModelUpdateUtil.updateModel(model,"operType","createStoreOid");
        //删除现有角色
        ModelUpdateUtil.delete(AdminGroupLink.class,
            QueryCondition.and(
                QueryCondition.eq("type",AdminGroup.Type_Role),
                QueryCondition.eq("orgGroup.oid",storeOid),
                QueryCondition.eq("admin.oid",userOid)
            )
        );
        if(null==operType||operType.length==0) return;
        //添加角色
        List<AdminGroupLink> ls=new ArrayList<>();
        OrgGroupView org=new OrgGroupView();
        org.setOid(storeOid);
        for(String ot : operType){
            AdminGroupLink l=new AdminGroupLink();
            l.setOid(GenerateID.generatePrimaryKey());
            l.setType(AdminGroup.Type_Role);
            l.setAdminGroup(new AdminGroup());
            l.getAdminGroup().setOid(ot);
            l.setAdmin(model);
            l.setOrgGroup(org);
            ls.add(l);
        }
        ModelUpdateUtil.insertModels(ls.toArray(new AdminGroupLink[0]));
        CacheUtil.clear(ModuleInfo.class);
        CacheUtil.clear(MenuInfo.class);
        CacheUtil.clear(AdminGroupPower.class);
    }

}
